package com.example.administrator.himalaya.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.administrator.himalaya.R;
import com.example.administrator.himalaya.activity.DetailsActivity;
import com.example.administrator.himalaya.adapter.CategoryAdapter;
import com.example.administrator.himalaya.adapter.DataAdapter;
import com.example.administrator.himalaya.callback.AdService;
import com.example.administrator.himalaya.callback.OnclickListner;
import com.example.administrator.himalaya.callback.gitHubService;
import com.example.administrator.himalaya.entity.categoryentity.AdEntity;
import com.example.administrator.himalaya.entity.categoryentity.BooksEntity;
import com.example.administrator.himalaya.entity.categoryentity.DataEntity;
import com.example.administrator.himalaya.entity.categoryentity.SortEntity;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentDicsoverCategory extends Fragment implements OnclickListner, ViewPager.OnPageChangeListener {
    private CoordinatorLayout coording;
    private RecyclerView recycler;
    private List<BooksEntity> list;
    private CategoryAdapter adapter;
    private ViewPager viewPager;
    private ImageView image;
    private List<ImageView> imageViewList;
    private DataAdapter dataAdapter;
    private List<ImageView> pointImage;
    private AdEntity adEntity;
    private String link;
    private List<DataEntity> data;

    private int[] images = new int[]{R.drawable.myspin_image_default_album_s,
            R.drawable.myspin_image_default_album_s, R.drawable.myspin_image_default_album_s};

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    viewPager.setCurrentItem(0);
                    break;
                case 1:
                    viewPager.setCurrentItem(1);
                    break;
                case 2:
                    viewPager.setCurrentItem(2);
                    break;
            }
        }
    };

    public FragmentDicsoverCategory() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_two, container, false);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        list = new ArrayList<>();
        coording = (CoordinatorLayout) view.findViewById(R.id.coording);
        recycler = (RecyclerView) view.findViewById(R.id.twofragment_recycler);
        viewPager = (ViewPager) view.findViewById(R.id.view_pager);
        GridLayoutManager manager = new GridLayoutManager(getContext(), 2);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 0) {
                    return 2;
                }
                return 1;
            }
        });
        recycler.setLayoutManager(manager);
        adapter = new CategoryAdapter(getContext(),this,list);
        recycler.setAdapter(adapter);

        Download();

    }

    //网络数据下载
    private void Download() {
        gitHubService service = new Retrofit.Builder()
                .baseUrl("http://mobile.ximalaya.com/mobile/discovery/v1/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(gitHubService.class);
        service.list("and-a1", "android", 13, 2).enqueue(new Callback<SortEntity>() {
            @Override
            public void onResponse(Call<SortEntity> call, Response<SortEntity> response) {
                SortEntity body = response.body();
                Log.d("123455", body.getList().size() + "");
                adapter.addAll(body.getList());
            }

            @Override
            public void onFailure(Call<SortEntity> call, Throwable t) {
                Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        final AdService adService = new Retrofit.Builder()
                .baseUrl("http://adse.ximalaya.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(AdService.class);
        adService.ad("android", "cata_index_banner", "wifi", 0, 4.3).enqueue(new Callback<AdEntity>() {

            @Override
            public void onResponse(Call<AdEntity> call, Response<AdEntity> response) {
                adEntity = response.body();
                data = response.body().getData();
                Log.d("1620", "onResponse: "+data.size());
                imageViewList = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    image = new ImageView(getContext());
                    image.setScaleType(ImageView.ScaleType.FIT_XY);
                    image.setImageResource(images[i]);
                    imageViewList.add(image);
                    Picasso.with(getContext()).load(adEntity.getData().get(i).getCover()).into(image);
                }
                dataAdapter =new DataAdapter(imageViewList,getContext(),data);
                viewPager.setAdapter(dataAdapter);
                Carousel();
            }
            @Override
            public void onFailure(Call<AdEntity> call, Throwable t) {
                Toast.makeText(getContext(),  t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    //事件监听
    @Override
    public void onclicklistener(int position) {
        int id = list.get(position).getId();
        Intent intent = new Intent(getContext(), DetailsActivity.class);
        intent.putExtra("id", id);
        startActivity(intent);
    }
    //自动轮播
    private void Carousel() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    for (int i = 0; i < imageViewList.size(); i++) {
                        try {
                            Thread.sleep(3000);
                            handler.sendEmptyMessage(i);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        }).start();
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < pointImage.size(); i++) {
            pointImage.get(i).setSelected(i == position);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        viewPager.removeOnPageChangeListener(this);
    }
}
